package com.iwhalecloud.citybrain.flow.platform.manager.application.utils;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @author lilh
 * @date 2019-02-20 22:47
 */
public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String sendHttpPost(String url, String json) throws RuntimeException {
        return sendHttpPost(url, json, "UTF-8");
    }

    private static String sendHttpPost(String url, String json, String encode) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost;
        String result = null;
        httpPost = new HttpPost(url);

        try {
            InputStreamEntity inputStreamEntity = new InputStreamEntity(new ByteArrayInputStream(json.getBytes(encode)), ContentType.APPLICATION_JSON);
            httpPost.setEntity(inputStreamEntity);
            HttpResponse response = httpclient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), encode);
            }
            return result;
        } catch (ClientProtocolException e) {
            logger.error("ClientProtocolException异常 : " + e);
        } catch (IOException e) {
            logger.error("IOException异常 :  " + e);
        } catch (Exception e) {
            logger.error("异常 :  " + e);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
